﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using SharePoint.Sunbox.Sandbox.Resources;

namespace SharePoint.Sunbox.Sandbox.CommentsWebPart
{
    public class CommentsEditorPart : EditorPart
    {
        private readonly DropDownList _ddlLists;
        public CommentsEditorPart()
        {
            _ddlLists = new DropDownList();
            _ddlLists.Items.Add(new ListItem(Properties.CommentWebPartNotSelectedText, "0"));
            _ddlLists.Items.AddRange(GetCommentsList().ToArray());
        }



        protected override void CreateChildControls()
        {
            Controls.Add(new LiteralControl(string.Format("<div class='UserSectionHead'>{0}:</div><div class='UserControlGroup'>", Properties.CommentsWebPartListPropertyTitle)));
            Controls.Add(_ddlLists);
            Controls.Add(new LiteralControl("</div>"));
        }
        public override bool ApplyChanges()
        {
            var commentsWebPart = WebPartToEdit as CommentsWebPart;
            if (commentsWebPart == null)
                return false;
            if (_ddlLists.SelectedValue == "0")
                return true;//custom list
            commentsWebPart.CommentsListName = _ddlLists.SelectedValue;
            commentsWebPart.CommentsTextFieldName = "CommentText";
            commentsWebPart.CommentsArticleIdFieldName = "ParentId";
            commentsWebPart.CommentsParentIdFieldName = "ParentCommentId";

            return true;
        }

        public override void SyncChanges()
        {
            var commentsWebPart = WebPartToEdit as CommentsWebPart;
            if (commentsWebPart == null)
                return;

            _ddlLists.SelectedValue = commentsWebPart.CommentsListName;
        }



        private IEnumerable<ListItem> GetCommentsList()
        {
            var web = SPContext.Current.Web;
            var commentedContentTypeId = new SPContentTypeId("0x010049ED740159334F0A9B3F191C2E8152DE");

            return from SPList list in web.Lists
                   where !list.Hidden
                   let isCommentedList = list.ContentTypes.Cast<SPContentType>().Count(c => c.Id.Parent == commentedContentTypeId) > 0
                   where isCommentedList
                   select new ListItem(list.Title, list.ID.ToString());

        }

    }
}
